/*
 * @Author: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @Date: 2025-07-01 10:47:18
 * @LastEditors: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @LastEditTime: 2025-09-30 16:00:11
 * @FilePath: \keep_motion_api\models\course.model.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const mongoose = require('mongoose'); 
const Schema = mongoose.Schema; 
const { escapeRegex } = require('@/utils');

// 课程模型
const courseSchema = new Schema({
  title: { type: String, required: true },
  description: String,
  instructor: { 
    type: Schema.Types.ObjectId, 
    ref: 'Admin',
    required: true 
  },
  category: {
    type: String,
    enum: ["fitness", "yoga", "strength", "cardio", "nutrition"],
    required: true
  },
  difficulty: {
    type: String,
    enum: ["beginner", "intermediate", "advanced"],
    default: "beginner"
  },
  cover_image: String,
  preview_video: String,
  price: { type: Number, default: 0 },
  discount_price: Number,
  duration: Number,
  sections: [{
    title: String,
    lessons: [{
      lesson_title: String,
      video_url: String,
      duration: Number,
      resources: [{
        name: String,
        url: String
      }]
    }]
  }],
  ratings: [{
    user_id: { type: Schema.Types.ObjectId, ref: 'User' },
    rating: { type: Number, min: 1, max: 5 },
    comment: String,
    date: { type: Date, default: Date.now }
  }],
  average_rating: { type: Number, default: 0 },
  enrolled_count: { type: Number, default: 0 },
  created_time: { type: Date, default: Date.now },
  updated_time: { type: Date, default: Date.now },
  status: {
    type: String,
    enum: ["draft", "published", "archived"],
    default: "draft"
  },
  tags: [String],
  related_plans: [{
    type: Schema.Types.ObjectId,
    ref: 'TrainingPlan'
  }]
});

courseSchema.statics.getCourses = async function (_id = '', title = '', category = '', difficulty = '', status = '', offset = 0, limit = 10) {
  try {
      const query = {};
      if (_id) {
        query._id = _id;
      }
      if (title) {
        const escapedTitle = escapeRegex(title);
        query.title = { $regex: escapedTitle, $options: 'i' };  
      }
      if(category) {
        query.category = category;
      }
      if(difficulty) {
        query.difficulty = difficulty;
      }
      if(status) {
        query.status = status;
      }
      // 先统计符合条件的记录总数
      const total = await this.countDocuments(query);
      // 再进行分页查询
      const rows = await this.aggregate([
        { $match: query },                   // 匹配查询条件
        { $skip: Number(offset) },           // 分页跳过
        { $limit: Number(limit) },           // 分页限制
        // 关联查询（相当于 populate）
        { $lookup: {
            from: 'admins',               // 关联的集合名（通常是模型名小写复数）
            localField: 'instructor',           // 本地关联字段
            foreignField: '_id',             // 关联集合的匹配字段
            as: 'instructorInfo'                   // 临时存储关联数据的字段
          }
        },
        { $unwind: '$instructorInfo' },            // 展开数组（如果是一对一关系）
        // 投影（展平字段 + 筛选）
        { $project: {
            // 保留原文档字段
            _id: 1, title: 1, description: 1, instructor: 1, category: 1, difficulty: 1, duration: 1, price: 1, discount_price: 1, status: 1, tags: 1,
            // 展平关联字段到顶层
            instructor_name: '$instructorInfo.nickname',     // 直接映射嵌套字段到顶层
            // 如需保留原type_id可添加: type_id: '$typeInfo._id'
          }
        }
      ]);
      return { rows, total };
    } catch (error) {
      throw { message: '获取课程列表失败', error };
    }
}

courseSchema.statics.getCourseDetail = async function (_id) {
  try {
    const course = await this.findById(_id);
    const { Admin } = require('../permission');
    const admin = await Admin.findById(course.instructor);
    // 等 计划表 完成后 需要补充计划的 联查
    return {
      ...course.toObject(),
      instructor_name: admin.nickname
    }
  } catch (error) {
    throw { message: '获取课程详情失败', error };
  }
}

courseSchema.statics.createCourses = async function (data) {
  try {
    return await this.create(data);
  } catch (error) {
    throw { message: '创建课程失败', error };
  }
}
courseSchema.statics.updateCourses = async function (id, data) {
  try {
    return await this.findByIdAndUpdate(id, data, { new: true });
  } catch (error) {
    throw { message: '更新课程失败', error };
  }
}
courseSchema.statics.deleteCourses = async function (id) {
  try {
    return await this.findByIdAndDelete(id);
  } catch (error) {
    throw { message: '删除课程失败', error };
  }
}
courseSchema.statics.publishCourses = async function (id) {
  try {
    const course = await this.findById(id);
    if (!course) {
      throw { message: '课程不存在', error };
    }
    if (course.status === 'published') {
      course.status = 'archived';
    } else {
      course.status = 'published';
    }
    return await course.save();
  } catch (error) {
    throw { message: '发布/取消发布课程失败', error };
  }
}
// 小程序  接口未完成
courseSchema.statics.searchCourses = async function (user_id, course_id) {
  return await this.updateOne({ user_id, course_id }, { published: true });
}
courseSchema.statics.getCoursesStats = async function (user_id, course_id) {
  return await this.updateOne({ user_id, course_id }, { published: true });
}
module.exports = mongoose.model('Course', courseSchema);